#include <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <vector>
#include <stack>
#include <queue>
#include <set>
using namespace std;
class UnionFind
{
public:
    UnionFind(int N) : N(N)
    {
        par = new int[N];
        fill(par, par + N, -1);
        size = new int[N];
        fill(size, size + N, 1);
    }
    int Find(int x)
    {
        if (par[x] == -1)
            return x;
        int parx = Find(par[x]);
        par[x] = parx;
        return parx;
    }
    void Union(int x, int y)
    {
        int parx = Find(x), pary = Find(y);
        if (parx == pary)
            return;
        if (size[parx] < size[pary])
        {
            par[parx] = pary;
            size[pary] += size[parx];
            size[parx] = 0;
        }
        else
        {
            par[pary] = parx;
            size[parx] += size[pary];
            size[pary] = 0;
        }
    }
    int NumOfConnectedComponent()
    {
        int ans = 0;
        for (int i = 0; i < N; ++i)
        {
            ans += (size[i] != 0 ? 1 : 0);
        }
        return ans;
    }

private:
    int *par, *size, N;
};
class Solution
{
public:
    int minSwapsCouples(vector<int> &row)
    {
        UnionFind uf(row.size());
        for (int i = 0; 2 * i < row.size(); ++i)
        {
            uf.Union(2 * i, 2 * i + 1);
            uf.Union(row[2 * i], row[2 * i + 1]);
        }
        return row.size() - uf.NumOfConnectedComponent();
    }
};